package ${packPath}.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zbx.database.constant.SystemTools;
import com.zbx.database.constant.Validator;
import com.zbxsoft.api.api.ApiService;
import com.zbxsoft.api.vo.ParamsVo;
import com.zbxsoft.api.vo.ResultEntity;
import com.zbxsoft.api.vo.ResultMsg;
import com.zbxsoft.passport.entity.Token;
import com.zbxsoft.rpc.client.RpcProtoclClient;
import com.zbxsoft.rpc.entity.InterfaceRegister;
import com.zbxsoft.rpc.util.JsonEntityParese;
import com.zbxsoft.rpc.util.XMLMapParse;
import com.zbxsoft.tools.StrUtil;
import com.zbxsoft.uct.common.ToolsUtil;

/**
 * description: Http或Https访问action
 * @Copyright(c)2014:北京中百信软件技术有限公司
*/
@Controller
@RequestMapping("${reqName}/service/")
public class ${restfullClassName} {
	@Autowired
	private ApiService ${reqName}Service;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("doService.action")
	public void doService(HttpServletRequest request, HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		String paramStr = request.getParameter("params");
		Map<String, Object> headMap = new HashMap<String, Object>();
		Map<String, Object> bodyMap = new HashMap<String, Object>();
		XMLMapParse.instance().xmlGetData(paramStr, headMap, bodyMap);
		vo.setMethodKey(headMap.get("MethodCode").toString());
		vo.setParams(bodyMap);
		getResultInfo(vo, request, response);
	}

	/**
	 * description:  系统统一接口(restfull--post)
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/doService", method = RequestMethod.POST)
	public void doServiceForRf(HttpServletRequest request, HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		String paramStr = request.getParameter("params");
		if (Validator.isNotNull(paramStr)) {
			Map<String, Object> headMap = new HashMap<String, Object>();
			Map<String, Object> bodyMap = new HashMap<String, Object>();
			XMLMapParse.instance().xmlGetData(paramStr, headMap, bodyMap);
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
		} else {
			String methodCode = request.getParameter("MethodCode");
			Map<String, Object> bodyMap = getRequestParam(request);
			vo.setMethodKey(methodCode);
			vo.setParams(bodyMap);
		}
		getResultInfo(vo, request, response);
	}

	/**
	 * description:  系统统一接口(restfull--get)
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/doService", method = RequestMethod.GET)
	public void serviceForRf(HttpServletRequest request, HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		String paramStr = request.getParameter("params");
		if (Validator.isNotNull(paramStr)) {
			Map<String, Object> headMap = new HashMap<String, Object>();
			Map<String, Object> bodyMap = new HashMap<String, Object>();
			XMLMapParse.instance().xmlGetData(paramStr, headMap, bodyMap);
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
		} else {
			String methodCode = request.getParameter("MethodCode");
			Map<String, Object> bodyMap = getRequestParam(request);
			vo.setMethodKey(methodCode);
			vo.setParams(bodyMap);
		}
		getResultInfo(vo, request, response);
	}

	private void getResultInfo(ParamsVo vo, HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		try {
			ResultEntity entity = ${reqName}Service.doService(vo);
			if (Validator.isEmpty(entity)) {
				entity = new ResultEntity();
				entity.setResult("false");
				entity.setMessage("接口调用失败！");
			}
			String callback = request.getParameter("callback");
			if (Validator.isNull(callback)) {
				String paramType = request.getParameter("ParamType");
				if ("json".equalsIgnoreCase(paramType))
					result = JsonEntityParese.instance().beanToJson(entity);
				else
					result = JsonEntityParese.instance().toXml(entity);
				response.setContentType("text/html; charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.print(result);
				out.flush();
			} else {///支持jsonp数据格式
				PrintWriter out = response.getWriter();
				response.setContentType("application/javascript");
				if (Validator.isEmpty(entity.getEntity())) {
					ResultMsg msg = new ResultMsg("F", "操作失败");
					JSONObject json = JSONObject.fromObject(msg);
					result = json.toString();
				} else {
					JSONObject json = JSONObject.fromObject(entity);
					result = json.toString();
				}
				out.print(callback + "(" + result + ")");
				out.flush();
			}
		} catch (Exception e) {
		}
	}

	@SuppressWarnings({ "rawtypes" })
	protected Map<String, Object> getRequestParam(HttpServletRequest request) {
		Map<String, Object> data = new HashMap<String, Object>();
		Set keSet = request.getParameterMap().entrySet();
		for (Iterator itr = keSet.iterator(); itr.hasNext();) {
			Map.Entry me = (Map.Entry) itr.next();
			String ok = String.valueOf(me.getKey());
			Object ov = me.getValue();
			String value = "";
			if ((ov instanceof String[])) {
				String[] vls = (String[]) ov;
				value = vls[0];
			} else {
				value = String.valueOf(ov);
			}
			if (StrUtil.isNotNull(value)) {
				try {
					if (value.equals(new String(value.getBytes("iso8859-1"), "iso8859-1"))) {
						value = new String(value.getBytes("iso8859-1"), "utf-8");
					}
				} catch (IOException e) {
				}
				data.put(ok, value);
			}
		}
		return data;
	}

}
